const ctxs = [];

const { mysql } = require('./qcloud')
function WS() {

}


WS.prototype.addClient = (ctx) => {
    //console.log(JSON.stringify(ctx.query.name))
    for (var index = 0; index < ctxs.length; index++) {
        if (ctxs[index].query.name == ctx.query.name) {
            //clients[index].colse();
            console.log(ctxs[index].query.name + " be closed!");
            ctxs[index].websocket.close();
            ctxs.splice(index, 1)
            break;
        }
    }

    ctxs.push(ctx);
    console.log(ctx.query.name + '  connected!')
    console.log("当前" + ctxs.length + '人在线')

    mysql.select('*').where({ toUserId: ctx.query.name }).from('message').then(res => {
        console.log(res)
        for (var i = 0; i < res.length; i++) {
            var data = res[i];
            data.extras = JSON.parse(data.extras)
            console.log(data.toUserId)
            
            ctx.websocket.send(JSON.stringify(data));

            mysql.where({ id: data.id }).from('message').del()
                .then((res) => {
                    console.log('删除成功' + res)
                }).catch(err => {
                    console.log('删除失败' + err)
                })
        }
    })
}
WS.prototype.send = (msg) => {

    try {

        var message = JSON.parse(msg);

        if (typeof (message) == 'object') {

            for (var index = 0; index < ctxs.length; index++) {
                if (ctxs[index].query.name == message.toUserId) {
                    console.log(message.fromUserId + ' 向 ' + message.toUserId + ' 发送消息')

                    message.createdAt = new Date();
                    console.log("消息内容为：" + message.message)
                    ctxs[index].websocket.send('chat:' + JSON.stringify(message));

                } else if (index == ctxs.length - 1) {
                    console.log('对方不在线')
                    //console.log(message)
                    mysql.insert({ fromUserName: message.fromUserName, fromUserId: message.fromUserId, fromUserAvator: message.fromUserAvator, toUserId: message.toUserId, toUserName: message.toUserName, toUserAvator: message.toUserAvator, message: message.message, type: message.type, createdAt: new Date(), extras: JSON.stringify(message.extras) }, 'id').into('message')
                        .then(() => {
                            console.log('插入成功')
                        })

                }

            }
        } else {

            throw 'message is not an object!'
        }

    } catch (err) {
        console.log('解析出现异常:' + err)
    }
}

WS.prototype.exit = (ctx) => {
    var index = ctxs.indexOf(ctx);
    if (index >= 0) {
        console.log(ctxs[index].query.name + ' closed!')
        ctxs.splice(index, 1);
    }

}

module.exports = new WS()